package com.test.multithread.sync;

public class Singleton {
    //问题1：下面的字段必须使用volatile，因为java对象创建可能有重排序的问题
    // 重排序的顺序：
    // 1.分配内存空间
    // 2.初始化对象
    // 3.将对象指向刚分配的内存空间
    //private static Singleton singleton; //error
    private volatile static Singleton singleton;  //correct
    private Singleton() {
    }
    /* 这是错误的写法，尽量不用synchronized修饰方法
    * public synchronized Singleton getInstance() {
        if (null == uniqueSingleton) {
            uniqueSingleton = new Singleton();
        }
        return uniqueSingleton;
    }
    * */
    public static Singleton getSingleton() {
        //每个线程先检验是否被初始化成功
        if (singleton == null) {
            //加上锁之后，再去检验一次确认是否被指向和初始化
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    /*public class Singleton {
        private volatile static Singleton uniqueSingleton;

        private Singleton() {
        }

        public Singleton getInstance() {
            if (null == uniqueSingleton) {
                synchronized (Singleton.class) {
                    if (null == uniqueSingleton) {
                        uniqueSingleton = new Singleton();
                    }
                }
            }
            return uniqueSingleton;
        }
    }*/
}
